package com.kacheap.controller;

import java.util.List;

import org.pf4j.Plugin;
import org.pf4j.PluginManager;
import org.pf4j.PluginWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/plugin/")
public class PluginController {

	@Autowired
	private PluginManager pluginManager;

	@GetMapping("execute")
	public String execute() {
		List<PluginWrapper> plugins = pluginManager.getPlugins();

		for (PluginWrapper pluginWrapper : plugins) {
			Plugin plugin = pluginWrapper.getPlugin();
			if (plugin != null) {
				plugin.start();
				plugin.stop();
			}
		}
		return "Successful";
	}

	@GetMapping("execute/{pluginName}")
	public String execute(@PathVariable() String pluginName) {
		PluginWrapper wrapper = pluginManager.getPlugin(pluginName);
		if (null == wrapper) {
			try {
				pluginManager.loadPlugins();
				
				wrapper = pluginManager.getPlugin(pluginName);
			} catch (Exception e) {
				System.err.println("插件加载失败 ==> " + e.getMessage());
			}
		}
		
		if (null == wrapper || null == wrapper.getPlugin()) {
			return "Successful";
		}

		Plugin plugin = wrapper.getPlugin();

		plugin.start();

		plugin.stop();

		return "Successful";
	}

}
